<template>
    <div class="treeBox">
      <el-row style="padding: 8px">
        <el-col :span="24">
          <el-button style="float:right;" @click="refsh" type="primary" size="medium">刷新</el-button>
        </el-col>
      </el-row>
      <el-row style="margin-top:5px">
        <vxe-table
          ref="mytable"
          :data="tableData"
          style="width: 100%; margin-bottom: 20px"
          row-id="id"
          :max-height="heightY"
          highlight-current-row
          :height="heightY"
          :indent="indentNumber"
          border
          :tree-config="{children: 'children', hasChild: 'isParent',lazy:true,loadMethod:load}"
        >
          <vxe-column
            field="name"
            title="目录名称"
            sortable
            width="700"
            tree-node
          />
          <vxe-column
            field="content3"
            title="序号"
            sortable
          />
          <vxe-column
            title="操作"
            align="center"
            header-align="center"
            width="600"
          >
            <template slot-scope="scope">
              <el-button
                plain
                type="primary"
                :disabled="selectAssessState != 1"
                @click="addTree(scope.row)"
              >
                添加下级
              </el-button>
              <el-button
                type="primary"
                plain
                :disabled="selectAssessState != 1"
                @click="hanldupdateSort(scope.row)"
              >
                调整下级排序
              </el-button>
              <el-button
                type="primary"
                plain
                :disabled="selectAssessState != 1"
                @click="updateTree(scope.row)"
              >
                修改
              </el-button>
              <el-button
                type="danger"
                plain
                :disabled="selectAssessState != 1"
                @click="deleteTreeDataById(scope.row)"
              >
                删除
              </el-button>
            </template>
          </vxe-column>
        </vxe-table>
        <!-- 分页 -->
        <div
          class="row"
          style="width: 100%; float: left; text-align: center; margin-top: 5px"
        />
      </el-row>
      <!-- 弹框 -->
      <el-dialog
        :title="form.treeTitle"
        :fullscreen="dialogFullscree"
        :visible.sync="dialogVisible"
        width="40%"
        class="showDialogClass"
        :close-on-click-modal="false"
        :before-close="handleClose"
      >
        <el-form
          ref="form"
          :model="form"
          label-width="190px"
        >
          <el-form-item label="选择目录">
            <el-cascader
              ref="cascader"
              :options="tableData"
              popper-class="gy-cascader"
              :props="{ value: 'id', label: 'name', checkStrictly: true }"
              size="small"
              :key='cascaderIdx'
              v-model="cascadrValue"
              :show-all-levels="false"
              @change="handleChange"
            />
          </el-form-item>
          <el-form-item :label="form.treeLabel">
            <el-input
              :disabled="false"
              v-model="form.name"
            />
          </el-form-item>
          <el-form-item label="排序">
            <el-input-number
              v-model.number="form.sort"
              :min="1"
              :max="999"
              label="只能是数字"
            />
          </el-form-item>
        </el-form>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button
            type="primary"
            @click="onSubmit"
          >
            {{ buttonText }}
          </el-button>
          <el-button @click="handleClose">
            取消
          </el-button>
        </span>
      </el-dialog>
      <updateSort 
         ref="updateSortRef"
         v-if="updateSortFlag"
         :sub-tree-data="subTreeData"
         :cascader-list="cascaderList"
         @refresh="getDataList"
         ></updateSort>
    </div>
  </template>
  
    <script>
    import { getTreeDataList, save, update, deleteTree } from "@/api/knowledge/diretory";
    import store from "@/store";
    import updateSort from "./updateSort";
  
    
    export default {
      name: `templateName`,
      components:{updateSort},
      data () {
        return {
          buttonText: `保存`,
          tableData: [],
          indentNumber: 24,
          // 表格数据
          dataList: [],
          heightY: `${window.innerHeight - 150}px`,
          dialogVisible: false,
          dialogFullscree: false,
          selectAssessState: 1,
          // 表单变量
          form: {
            treeLabel: ``,
            treeTitle: ``,
            id: null,
            code: ``,
            name: ``,
            type: ``,
            level: 0,
            sort: null,
            state: ``,
          },
          addRow: ``,
          updateRow: ``,
          fileBussinessTypeCode: `111`,
          maps: new Map(),
          updateSortFlag:false,
          subTreeData: [], // 子节点数据
          cascadrValue:[],
          cascaderIdx:0,
          nodeId:"",
          treeIndex:"",
          cascaderList:[],
          treeIndexDesc:"",
          drawer:false,
          checkedNodes:[],
        };
      },
      created () {
        this.getDataList();
        this.init();
      },
      watch:{
        cascadrValue() {
          if (this.$refs.cascader) {
              this.$refs.cascader.dropDownVisible = false
          }
        },
        tableData(newVal) {
              this.cascaderIdx++;
        },
      },
      //方法集合
      methods: {
        init(){
          this.updateSortFlag = true;
        },
        load({ row }) {
          return new Promise((resolve) => {
            setTimeout(() => {
              const params = {
                userId: store.getters.user_id.toString(),
                token: store.getters.token.toString(),
                userName: store.getters.userName.toString(),
                data: {
                  fileBussinessTypeCode: this.fileBussinessTypeCode,
                  fileDiretoryId: row.id,
                },
              };
              getTreeDataList(params).then((data) => {
                if (data.result === true) {
                  // 新增：将数据存储到 maps 属性中
                  this.maps.set(row.id, { row, children: data.resultdata.data });
                  resolve(data.resultdata.data);
                } else {
                  this.$message({
                    type: `warning`,
                    message: `获取信息出错`,
                  });
                }
              });
            }, 1000);
          });
        },
        getDataList () {
          const params = {
            userId: store.getters.user_id.toString(),
            token: store.getters.token.toString(),
            userName: store.getters.userName.toString(),
            data: {
              fileBussinessTypeCode: this.fileBussinessTypeCode,
              fileDiretoryId: null,
            },
          };
          getTreeDataList(params).then((data) => {
            if (data.result === true) {
              this.tableData = data.resultdata.data;
            }
            else {
              this.$message({
                type: `warning`,
                message: `获取信息出错`,
              });
            }
          });
        },
        refsh(){
          this.$nextTick(() => {
            this.tableData = [];
          })
          this.getDataList();
        },
        getTreeData () {
          const params = {
            userId: store.getters.user_id.toString(),
            token: store.getters.token.toString(),
            userName: store.getters.userName.toString(),
            data: {
              fileBussinessTypeCode: this.fileBussinessTypeCode,
              fileDiretoryId: null,
            },
          };
          getTreeDataList(params).then((data) => {
            if (data.result === true) {
              this.treedata = data.resultdata.data;
            }
            else {
              this.$message({
                type: `warning`,
                message: `获取信息出错`,
              });
            }
          });
        },
        // tree的懒加载数据
        loadNode (node, resolve) {
          if (node.level === 0) {
            return resolve(this.treedata);
          }
          if (node.level > 9999) return resolve([]);
          // 请求子节点数据
          setTimeout(() => {
            const params = {
              userId: store.getters.user_id.toString(),
              token: store.getters.token.toString(),
              userName: store.getters.userName.toString(),
              data: {
                fileBussinessTypeCode:this.fileBussinessTypeCode,
                fileDiretoryId: node.data.id,
              },
            };
            getTreeDataList(params).then((data) => {
              if (data.result === true) {
                node.childNodes = [...node.childNodes, ...data.resultdata.data];
                const updatedChildren = node.childNodes.map((child) => {
                  child.checked =
                    this.checkable &&
                    this.checkedNodes.some((node) => node.id === child.id);
                  return child;
                });
                resolve(updatedChildren);
              }
              else {
                this.$message({
                  type: `warning`,
                  message: `获取信息出错`,
                });
              }
            });
          }, 500);
        },
        //点击tree树进行选择
        handleNodeClick (data, b, c) {
          this.treeIndexDesc = data.name;
          this.$refs.tclb.closeDrawer();
        },
        handleCloseDrawer (done) {
          done();
        },
        openDrawer () {
          this.drawer = true;
        },
        // 调整下级排序
        hanldupdateSort(data) {
          this.updateSortFlag = true;
          this.cascaderList = this.tableData
          console.log(this.cascaderList,"this.cascaderList")
          const params = {
            userId: store.getters.user_id.toString(),
            token: store.getters.token.toString(),
            userName: store.getters.userName.toString(),
            data: {
              fileBussinessTypeCode: this.fileBussinessTypeCode,
              fileDiretoryId: data.id,
            },
          };
          getTreeDataList(params).then((res) => {
            if (res.result === true) {
              this.subTreeData = res.resultdata.data;
              this.$nextTick(() => {
                this.$refs.updateSortRef.init(data);
              });
            } else {
              this.$message({
                type: "warning",
                message: "获取信息出错",
              });
            }
          });
        },
        deleteTreeDataById (row) {
          this.$confirm(`是否确认删除?`, `提示`, {
            confirmButtonText: `确定`,
            cancelButtonText: `取消`,
            type: `warning`,
          }).then(() => {
            const params = {
              'userId': store.getters.user_id.toString(),
              'token': store.getters.token.toString(),
              userName: store.getters.userName.toString(),
              data: {
                fileDiretoryId: row.id,
                fileBussinessTypeCode: this.fileBussinessTypeCode,
              },
            }
            deleteTree(params).then((data) => {
              if (data.result === true) {
                this.$message({
                  type: `success`,
                  message: `删除成功`,
                })
              }
            })
          })
            .catch((err) => {
              this.$message({
                type: `info`,
                message: `删除已取消`,
              })
            })
        },
        handleChange() {
        },
        getAllParents(id) {
          let list = this.tableData
          function getParentTree(id, tree) {
            let arr = [];
            for (let i = 0; i < tree.length; i++) {
              let item = tree[i];
              arr = [];
              arr.push(item);
              if (id == item.id) {
                return arr;
              } else {
                if (item.children && item.children.length > 0) {
                  arr = arr.concat(getParentTree(id, item.children ? item.children : []));
                  if (arr.map((item2) => (item2 ? item2.id : "")).includes(id)) {
                    return arr;
                  }
                }
              }
            }
          }
          return getParentTree(id, list)
        },
        //新增下级按钮
        addTree (row) {
          this.addRow = row;
          this.dialogVisible = true;
          this.form.treeTitle = `新增下级目录`
          this.form.treeLabel = `新增目录名称`
          this.form.state=`add`;
          this.form.name=``;
          this.cascadrValue = [];
  
          if(row.pid === '0') {
            this.cascadrValue = [row.id]
          } else {
            let arr = this.getAllParents(row.id)
            this.cascadrValue = arr.map(e => e.id)
          }
        },
        // 修改按钮
        updateTree (row) {
          this.updateRow = row;
          this.dialogVisible = true;
          this.form.name = row.name;
          this.form.sort = row.content3;
          this.form.treeTitle = `修改目录信息`
          this.form.treeLabel = `目录名称`
          this.form.state=`upd`;
          // this.cascadrValue = row.id
  
          if(row.pid === '0') {
            this.cascadrValue = [row.id]
          } else {
            let arr = this.getAllParents(row.pid)
            this.cascadrValue = arr.map(e => e.id)
          }
        },
        onSubmit () {
          if (this.form.name == `` || this.form.name == null) {
            this.$message({
              message: `请输入目录名称！`,
              type: `error`,
            })
            return false;
          }
          
          const params = {
            'userId': store.getters.user_id.toString(),
            'token': store.getters.token.toString(),
            userName: store.getters.userName.toString(),
            "data": {
              fileBussinessTypeCode: this.fileBussinessTypeCode,
              fileDiretoryName: this.form.name,
              diretoryParentId: this.addRow.id,
              diretoryOrder: this.form.sort,
            },
          }
          if (this.form.state === `add`) {
            let pid = this.cascadrValue[this.cascadrValue.length - 1]
            params.data.diretoryParentId = pid
            save(params).then((data) => {
              if (data.result === true) {
                this.$message({
                  type: `success`,
                  message: `操作成功`,
                })
                this.dialogVisible = false;
              }
              else {
                this.$message({
                  type: `warning`,
                  message: `操作失败`,
                })
              }
            })
          }
          else if (this.form.state === `upd`) {
            const param = {
              'userId': store.getters.user_id.toString(),
              'token': store.getters.token.toString(),
              userName: store.getters.userName.toString(),
              "data": {
                fileDiretoryId: this.updateRow.id,
                fileBussinessTypeCode: this.fileBussinessTypeCode,
                fileDiretoryName: this.form.name,
                diretoryParentId: this.updateRow.pid,
                diretoryOrder: this.form.sort,
              },
            }
            let pid = this.cascadrValue[this.cascadrValue.length - 1]
            param.data.diretoryParentId = pid
            update(param).then((data) => {
              if (data.result === true) {
                this.$message({
                  type: `success`,
                  message: `修改成功`,
                })
                this.dialogVisible = false;
              }
              else {
                this.$message({
                  type: `warning`,
                  message: `修改失败`,
                })
              }
            })
          }
        },
        cancel () {
          this.dialogVisible = false;
          this.form = {
            id: ``,
            code: ``,
            name: ``,
            type: ``,
            level: ``,
            sort: 0,
            treeTitle: ``,
            treeLabel: ``,
            state: ``,
          }
        },
        handleClose () {
          this.cancel();
        },
      },
    };
  </script>
  
    <style scoped lang="scss">
    .treeBox{
      height: calc(100vh - 124px);
      background: white;
    }
  </style>
  <style>
  .gy-cascader{
    width: auto;
    overflow: scroll;
  }
  </style>
  